﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Web.UI.WebControls.WebParts;
using System.Windows;
using DataFileApplication_WPF.Common;


namespace DataFileApplication_WPF.Models
{
    [Serializable]
    public class TreeItemStruct : NotifyPropertyChangedBase
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                //判断是否更改名称，若更改  移除旧名称
                //if (OriginalName != null && Parent != null)
                //{
                //    Parent.NamesHashSet.Remove(OriginalName);
                //    //判断新名称是否重名
                //    if (!Parent.NamesHashSet.Add(value))
                //    {
                //        Parent.NamesHashSet.Add(OriginalName);
                //        return;
                //    }
                //}
                _name = value;
                RaisePropertyChanged();
            }
        }

        public HashSet<string> NamesHashSet { get; set; }

        public string ImagePath { get; set; }



        public TreeItemStruct Parent { get; set; }

        public int ArrayIndex { get; set; }

        public bool IsArray { get; set; }


        //treeview中存储的DataGrid结构
        private DataGridStruct _DataGridStructOfTreeItem;
        public DataGridStruct DataGridStructOfTreeItem
        {
            get { return _DataGridStructOfTreeItem; }
            set
            {
                _DataGridStructOfTreeItem = value;
                RaisePropertyChanged();
            }
        }

        //存储节点的名称，取消重命名时使用
        public string OriginalName { get; set; }


        //节点是否重命名状态标识
        private bool _isRename;
        public bool IsRename
        {
            get { return _isRename; }
            set
            {
                if (_isRename != value)
                {
                    if (value)
                    {
                        OriginalName = Name;
                    }
                    _isRename = value;
                    RaisePropertyChanged();

                }
            }
        }

        //+
        private string _iconName;

        public string IconName
        {
            get { return _iconName; }
            set { _iconName = value; }
        }
        public ObservableCollection<TreeItemStruct> Children { get; set; }
        public event Action<string> ChildAddDuplicateName;

        public TreeItemStruct()
        {
            Children = new ObservableCollection<TreeItemStruct>();
            NamesHashSet = new HashSet<string>();
            DataGridStructOfTreeItem = new DataGridStruct();


            //集合数量发生变化时触发，如增减元素  判断元素名称
            Children.CollectionChanged += (sender, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (TreeItemStruct newItem in e.NewItems)
                    {
                        //集合添加元素时，订阅该元素Key变化，Key变化时，判断是否重名
                        newItem.PropertyChanged += Item_PropertyChanged;

                        if (string .IsNullOrEmpty(newItem.OriginalName))
                        {
                            newItem.OriginalName = newItem.Name;
                        }
                      
                        string tempName = newItem.Name.ToString();

                        //// 如果名称已存在，直接返回
                        //if (NamesHashSet.Contains(tempName))
                        //{
                        //    // 延迟到事件处理完成后再移除
                        //    System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        //    {
                        //        Children.Remove(newItem);
                        //        ChildAddDuplicateName?.Invoke(tempName);
                        //    }));
                        //    return;
                        //}

                        // 如果名称已存在，添加后缀以避免重复
                        while (true)
                        {
                            if (NamesHashSet.Add(tempName))
                            {
                                newItem.Name = tempName;
                                //确认值后将OriginalKey赋值
                                newItem.OriginalName = tempName;
                                break;
                            }
                            tempName = tempName + "_copy";
                        }
                    }
                }
                else if (e.Action == NotifyCollectionChangedAction.Remove)
                {
                    foreach (TreeItemStruct oldItem in e.OldItems)
                    {
                        oldItem.PropertyChanged -= Item_PropertyChanged;
                        NamesHashSet.Remove(oldItem.Name);
                    }       
                  
                }
                else if (e.Action == NotifyCollectionChangedAction.Replace)
                {

                }
            };
        }

        private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName ==nameof(TreeItemStruct.Name))
            {
                var item = sender as TreeItemStruct;
                if (item == null) { return; }
                // 判断是否有重名
                int count = Children.Count(x => x.Name == item.Name);
                if (count > 1)
                {
                    System.Windows.MessageBox.Show($"Key \"{item.Name}\" 已存在，请修改为唯一值。");
                    // 还原Key为原值
                   
                   
                        item.Name = item.OriginalName;
                  
                }
                else
                {
               
                    // 如果没有重名，更新 NamesHashSet
                    //if (item.Parent != null)
                    //{
                    //    item.Parent.NamesHashSet.Remove(item.OriginalName);
                    //    item.Parent.NamesHashSet.Add(item.Name);
                    //}
                }
            }
        }

        public TreeItemStruct Clone()
        {
            // 创建一个新的 TreeItemStruct 对象
            var cloned = new TreeItemStruct
            {
                Name = this.Name,
                ImagePath = this.ImagePath,
                Parent = null, // 避免循环引用
                ArrayIndex = this.ArrayIndex,
                IsArray = this.IsArray,
                NamesHashSet = new HashSet<string>(this.NamesHashSet),
                IconName = this.IconName,
                IsRename = this.IsRename,
                OriginalName = this.OriginalName
            };

            // 递归克隆 DataGridStructOfTreeItem 属性
            if (this.DataGridStructOfTreeItem != null)
            {
                cloned.DataGridStructOfTreeItem = this.DataGridStructOfTreeItem.Clone();
            }

            // 递归克隆 Children 集合
            cloned.Children = new ObservableCollection<TreeItemStruct>();
            foreach (var child in this.Children)
            {
                var clonedChild = child.Clone();
                clonedChild.Parent = cloned;
                cloned.Children.Add(clonedChild);
            }
            return cloned;
        }

    }

}
